package cn.itcast.service.cargo.impl;

import cn.itcast.dao.cargo.ExportDao;
import cn.itcast.dao.cargo.InvoiceDao;
import cn.itcast.dao.cargo.ShippingOrderDao;
import cn.itcast.domain.cargo.Export;
import cn.itcast.domain.cargo.Invoice;
import cn.itcast.domain.cargo.InvoiceExample;
import cn.itcast.domain.cargo.ShippingOrder;
import cn.itcast.service.cargo.InvoiceService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service
public class InvoiceServiceImpl implements InvoiceService {
    @Autowired
    private InvoiceDao invoiceDao;
    @Autowired
    private ShippingOrderDao shippingOrderDao;
    @Autowired
    private ExportDao exportDao;

    @Override
    public PageInfo findAll(String id, int pageNum, int size) {
        PageHelper.startPage(pageNum, size);
        InvoiceExample invoiceExample = new InvoiceExample();
        invoiceExample.createCriteria().andCompanyIdEqualTo(id);
        List<Invoice> list = invoiceDao.selectByExample(invoiceExample);
        return new PageInfo(list);
    }

    @Override
    public void save(Invoice invoice) {
        //保存发表状态  并设置委托单状态为3  shippingOrder此时不能取消状态
        String id = invoice.getInvoiceId();
        invoiceDao.insert(invoice);
        ShippingOrder shippingOrder = shippingOrderDao.selectByPrimaryKey(id);
        shippingOrder.setState(2);
        shippingOrderDao.updateByPrimaryKeySelective(shippingOrder);
        //修改报运单状态
        Export export = exportDao.selectByPrimaryKey(id);
        export.setState(4);
        exportDao.updateByPrimaryKeySelective(export);

    }

    @Override
    public Invoice findById(String id) {
        return invoiceDao.selectByPrimaryKey(id);
    }

    @Override
    public void update(Invoice invoice) {
        //更新发票数据
        invoiceDao.updateByPrimaryKeySelective(invoice);
    }


    @Override
    public void deleteById(String id) {
        invoiceDao.deleteByPrimaryKey(id);
        //修改委托单的状态为  已上报
        ShippingOrder shippingOrder = shippingOrderDao.selectByPrimaryKey(id);
        shippingOrder.setState(1);
        shippingOrderDao.updateByPrimaryKeySelective(shippingOrder);

    }

    @Override
    public void cancel(String id) {
        //发票id 修改状态
        Invoice invoice = invoiceDao.selectByPrimaryKey(id);
        invoice.setState(0);//变为草稿
        invoiceDao.updateByPrimaryKeySelective(invoice);
    }

    @Override
    public void submit(String id) {
        //发票id 修改状态
        Invoice invoice = invoiceDao.selectByPrimaryKey(id);
        invoice.setState(1);//变为已提交   shippingOrder此时不能取消状态
        invoiceDao.updateByPrimaryKeySelective(invoice);
    }
}
